//
//  BCFriendsViewController.m
//  BCVersion
//
//  Created by ZhaoXiang on 3/3/14.
//  Copyright (c) 2014 Jungle. All rights reserved.
//

#import "BCFriendsViewController.h"
#import "BCNetworkClient.h"
#import "UIImageView+WebCache.h"
#import "FriendCell.h"
#import "MJRefresh.h"
#import "BCProgressHUD.h"
#if !BCM_VERSION
#import "BCManagerInfoViewController.h"
#endif
@interface NSDictionary (name)

@end

@implementation NSDictionary (name)

- (NSString*)name
{
    return self[@"name"];
}

@end



@interface BCFriendsViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(readwrite, copy, nonatomic) NSArray *tableData;
@property (nonatomic, strong)  MJRefreshHeaderView *header;
@end

@implementation BCFriendsViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self)
    {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
#if BCM_VERSION
    CGFloat y = self.segmentedControl.frame.origin.y;
    self.tableView.frame = CGRectMake(0, y, self.view.frame.size.width, self.view.frame.size.height - y);
    [self.segmentedControl removeFromSuperview];
#endif

    
    [self.tableView registerClass:[FriendCell class] forCellReuseIdentifier:@"Cell"];
    [self.navigationController setNavigationBarHidden:YES];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    [BCProgressHUD showWithTile:@"下载中" animated:YES];

    __weak typeof(self)weakSelf = self;
    _header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [BCNetworkClient userFiends:USER_MANAGER.auth
                               type:@"bind"
                              start:0
                              limit:0
                            success:^(NSNumber *total, NSArray *friends) {
            weakSelf.tableData = [weakSelf partitionObjects:friends
                            collationStringSelector:@selector(name)];
            [weakSelf.tableView reloadData];
            [refreshView endRefreshing];
            [BCProgressHUD hideAnimated:YES];
        } failure:^(NSError *error) {
            [refreshView endRefreshing];
            [BCProgressHUD hideWithError:error animated:YES];
        }];
    };
    //[header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self reloadFriends];
}


- (void)reloadFriends
{
    [BCProgressHUD showWithTile:@"下载中" animated:YES];

    [BCNetworkClient userFiends:USER_MANAGER.auth type:@"bind" start:0 limit:0 success:^(NSNumber *total, NSArray *friends) {
        self.tableData = [self partitionObjects:friends collationStringSelector:@selector(name)];
        [self.tableView reloadData];
        [BCProgressHUD hideAnimated:YES];
    } failure:^(NSError *error) {
        [BCProgressHUD hideWithError:error animated:YES];
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}

-(NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector

{
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    NSInteger sectionCount = [[collation sectionTitles] count]; //section count is take from sectionTitles and not sectionIndexTitles
    NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount];
    
    //create an array to hold the data for each section
    for(int i = 0; i < sectionCount; i++)
    {
        [unsortedSections addObject:[NSMutableArray array]];
    }
    
    //put each object into a section
    for (id object in array)
    {
        NSInteger index = [collation sectionForObject:object collationStringSelector:selector];
        [[unsortedSections objectAtIndex:index] addObject:object];
    }
    
    NSMutableArray *sections = [NSMutableArray arrayWithCapacity:sectionCount];
    
    //sort each section
    for (NSMutableArray *section in unsortedSections)
    {
        [sections addObject:[collation sortedArrayFromArray:section collationStringSelector:selector]];
    }
    
    return sections;
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //we use sectionTitles and not sections
    return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] count];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.tableData objectAtIndex:section] count];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    BOOL showSection = [[self.tableData objectAtIndex:section] count] != 0;
    //only show the section title if there are rows in the section
    return (showSection) ? [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section] : nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    FriendCell * friendCell = (FriendCell*)cell;
    
    id friend = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    friendCell.nameLabel.text = friend[@"name"];
    
    [friendCell.avatarImageView setImageWithURL:[NSURL URLWithString:friend[@"avatar"]]];
    
    return friendCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
#if BCM_VERSION
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
#else
    __weak NSDictionary *dic = (NSDictionary *)[[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    BCManagerInfoViewController *info = [[BCManagerInfoViewController alloc]initWithUid:[dic valueForKey:@"uid"]];
    [self.navigationController pushViewController:info animated:YES];
#endif
}


- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    //sectionForSectionIndexTitleAtIndex: is a bit buggy, but is still useable
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

- (void)dealloc
{
    [_header free];
}
@end
